﻿using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Windows.Data;
using BusinessConfiguration;
using System.Windows;

namespace Converter
{
    public class LocalizationConverter : IValueConverter
    {
        /// <summary>
        /// The Resource Manager loads the resources out of the executing assembly (and the XAP File where there are embedded)
        /// </summary>
        private static readonly ResourceManager globalresourceManager = 
            new ResourceManager("csla4Skeleton.UI.SL.Resources.ControlLocalization.Resources",
                                Assembly.GetExecutingAssembly());
        public static ResourceManager GlobalResourceManager
        {
            get { return globalresourceManager; }
        }

        /// <summary>
        /// Use this property to specify the culture
        /// </summary>
        private static CultureInfo uiCulture = new CultureInfo(Configuration.CultureInfo);
        public CultureInfo UiCulture
        {
            get { return uiCulture; }
            set { uiCulture = value; }
        }

        /// <summary>
        /// This method returns the localized string of the given resource.
        /// </summary>
        public string Get(string resource)
        {
            if(LocalResourceManager == null)
                return globalresourceManager.GetString(resource, uiCulture);

            string result = LocalResourceManager.GetString(resource, UiCulture);
            if (result == null || result == "")
            {
                result = globalresourceManager.GetString(resource, uiCulture);
            }
            return result;            
        }

        public ResourceManager LocalResourceManager { get; set; }
				 
        #region IValueConverter Members

        /// <summary>
        /// This method is used to bind the silverlight component to the resource. 
        /// </summary>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var reader = (LocalizationConverter)value;
            return reader.Get((string)parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // ConvertBack is not used, because the Localization is only a One Way binding
            throw new NotImplementedException();
        }

        #endregion
    }
}